package com.iteaj.util.core;

import com.iteaj.util.http.HttpAdapter;
import com.iteaj.util.http.HttpRequestConfig;
import com.iteaj.util.http.SSLContextManager;
import com.iteaj.util.http.adapter.HttpClientAdapter;
import com.iteaj.util.http.adapter.JdkHttpAdapter;
import com.iteaj.util.json.JsonAdapter;
import com.iteaj.util.xml.Jaxb2Adapter;
import com.iteaj.util.xml.XmlAdapter;

/**
 * create time: 2018/4/7
 *  项目里面一些常用的工具的默认配置管理
 *  注意：这些配置信息请在项目启动的时候进行配置好, 在项目运行的时候最好不要更改
 * @author iteaj
 * @version 1.0
 * @since JDK1.7
 */
public class UtilsFactory {

    private static Object lock = new Object();
    private static XmlAdapter defaultXmlAdapter;
    private static JsonAdapter defaultJsonAdapter;
    private static HttpAdapter defaultHttpAdapter;
    private static SSLContextManager defaultSslManager;
    private static HttpRequestConfig defaultRequestConfig;

    static {
        defaultXmlAdapter = new Jaxb2Adapter();
        //初始化默认的Https证书管理
        defaultSslManager = new SSLContextManager();
        //初始化默认的Http请求配置
        defaultRequestConfig = HttpRequestConfig.getDefault();
    }

    public static XmlAdapter getDefaultXmlAdapter() {
        return defaultXmlAdapter;
    }

    public static void setDefaultXmlAdapter(XmlAdapter defaultXmlAdapter) {
        UtilsFactory.defaultXmlAdapter = defaultXmlAdapter;
    }

    public static HttpAdapter getDefaultHttpAdapter() {
        if(null != defaultHttpAdapter)
            return defaultHttpAdapter;

        synchronized (lock) {
            if(null != defaultHttpAdapter)
                return defaultHttpAdapter;
            try {
                defaultHttpAdapter = HttpClientAdapter.instance();
            } catch (Throwable e) {
                defaultHttpAdapter = new JdkHttpAdapter();
            }

            return defaultHttpAdapter;
        }
    }

    public static void setDefaultHttpAdapter(HttpAdapter defaultHttpAdapter) {
        if(UtilsFactory.defaultHttpAdapter == null)
            UtilsFactory.defaultHttpAdapter = defaultHttpAdapter;
    }


    public static HttpRequestConfig getDefaultRequestConfig() {
        if(defaultRequestConfig == null)
            return HttpRequestConfig.getDefault();

        return defaultRequestConfig;
    }

    public static void setDefaultRequestConfig(HttpRequestConfig defaultRequestConfig) {
        UtilsFactory.defaultRequestConfig = defaultRequestConfig;
    }

    public static SSLContextManager getDefaultSslManager() {
        return defaultSslManager;
    }

    public static void setDefaultSslManager(SSLContextManager defaultSslManager) {
        UtilsFactory.defaultSslManager = defaultSslManager;
    }

}
